package fl.ass.service.api;

import cmm.comm.facade.upload.api.IUploadApiService;
import cmm.comm.facade.upload.condition.SysUlFilesRecQueryCondition;
import cmm.comm.facade.upload.dto.SysUlFilesRecDTO;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.finance.api.IFinLoanInfoApiService;
import cn.fl.finance.api.IFinPayApplyInfoApiService;
import cn.fl.finance.api.IFinPayDtlApiService;
import cn.fl.finance.condition.FinPayApplyInfoQC;
import cn.fl.finance.condition.FinPayDtlQC;
import cn.fl.finance.constant.FinFlowDynamicTableConstant;
import cn.fl.finance.constant.FinPayApplyInfoConstant;
import cn.fl.finance.dto.FinLoanInfoDTO;
import cn.fl.finance.dto.FinPayApplyInfoDTO;
import cn.fl.finance.dto.FinPayDtlDTO;
import cn.fl.project.constant.PrjBscInfoConstant;
import com.alibaba.fastjson.JSON;
import com.lionbridge.activiti.WorkflowClient;
import fl.ass.facade.api.IAssTrailCarApi;
import fl.ass.facade.api.ITrailerApplicationFlowFactoryApi;
import fl.ass.facade.constant.AssFileConstant;
import fl.ass.facade.constant.InterfaceConstants;
import fl.ass.facade.dto.*;
import fl.ass.service.dao.AssTrailCarDMapper;
import fl.ass.service.service.IAssParkingMgService;
import fl.ass.service.service.IAssTrailCarDService;
import fl.flow.facade.flow.constant.FlowConstant;
import fl.flow.facade.flow.dto.FlowCompleteParamsDTO;
import fl.flow.facade.flow.service.impl.FlowBusnessServiceImpl;
import fl.flow.service.flow.service.ISysFlowSHService;
import fl.inf.facade.api.IBFSApiService;
import fl.inf.facade.api.IWarrantApiService;
import fl.inf.facade.dto.InfBfsPayDTO;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 拖车申请流程回调接口实现类
 * @author KANGFENGCUI
 *
 */
@Service
public class TrailerApplicationFlowFactoryApi extends FlowBusnessServiceImpl implements ITrailerApplicationFlowFactoryApi {

	/**
	 * 流程启动历史服务
	 */
	@Autowired
	private ISysFlowSHService sysFlowSHService;
	/**
	 * 拖车服务
	 */
	@Autowired
	private IAssTrailCarApi assTrailCarApi;
	/**
	 * 上传下载服务
	 */
	@Autowired
	private IUploadApiService uploadApiService;

	/**
	 *
	 */
	@Autowired
	private AssTrailCarDMapper assTrailCarDMapper;
	/**
	 *权证
	 */
	@Autowired
	private IWarrantApiService warrantApiService;
	
	@Autowired
	private IBFSApiService bFSApiService;
	
	@Value("${pay.environment}")
    private String env;
	
	@Autowired
	private IFinPayDtlApiService finPayDtlApiService;

	@Autowired
	private IAssParkingMgService assParkingMgService;
	
	@Autowired
	private IFinPayApplyInfoApiService finPayApplyInfoApiService;

	@Autowired
    private IAssTrailCarDService assTrailCarDService;
	
	
	@Override
	public Map<String, Object> executeBefore(FlowCompleteParamsDTO flowCompleteParamsDTO) throws BaseException {
		Map<String, Object> parms = new HashMap<String, Object>();
		String procDefKey = flowCompleteParamsDTO.getProcDefKey();//流程KEY
		String taskDefKey = flowCompleteParamsDTO.getTaskDefKey();//任务KEY
		String branchKey = flowCompleteParamsDTO.getBranchKey();//分支KEY
		String procInstId = flowCompleteParamsDTO.getProcInstId();
		Long trailer_id = flowCompleteParamsDTO.getBusinessKey();
		BaseLogUtils.newLogger("拖车申请流程回调接口").setBussinessId("trailer_id:" + trailer_id).info();
		if("FLOW_0000_017_001".equals(procDefKey)&&StringUtils.isNotEmpty(taskDefKey)&&StringUtils.isNotEmpty(branchKey)){
			MessageDTO<String>  result;
			MessageDTO<AssTrailCarMDTO> messageDTO  = assTrailCarApi.findAssTrailCarMasterById(trailer_id);
			AssTrailCarMDTO assTrailCarMDTO = messageDTO.getData();
			List<AssTrailCarDInfDTO> infoList = new ArrayList<AssTrailCarDInfDTO>();
			//拖车明细数据
			List<Long> detailIdList = new ArrayList<Long>();
			List<AssTrailCarDDTO> assTrailCarDDTOList = assTrailCarApi.findTrailCarDetailListById(trailer_id).getDatas();
			for (AssTrailCarDDTO assTrailCarDDTO : assTrailCarDDTOList) {
				detailIdList.add(assTrailCarDDTO.getId());
			}
			
			if(branchKey.equals("FLOW_0000_017_001_004_001")){//事业部审核（重卡、专车）:点击通过
				/**
				 * 1.检验借款金额是否>0 2.检验是否是专车事业部且拖车费是否大于5000
				 */
				int BACK_AMT_FLAG = BaseConstant.IS_YESNO_NO;
				int ZC_BACK_AMT_FLAG = BaseConstant.IS_YESNO_NO;
				for (AssTrailCarDDTO assTrailCarDDTO : assTrailCarDDTOList) {
					if (assTrailCarDDTO.getBackAmt() != null) {
						Long backAmt = assTrailCarDDTO.getBackAmt();
						String buOrgCd = assTrailCarDDTO.getBuOrgCd();
						if (PrjBscInfoConstant.CODE_BU_ORG_CD_ZC.equals(buOrgCd) && backAmt / 100 >= 5000) {
							ZC_BACK_AMT_FLAG = BaseConstant.IS_YESNO_YES;
						} else if ( PrjBscInfoConstant.CODE_BU_ORG_CD_QK.equals(buOrgCd) && backAmt > 0) {
                            ZC_BACK_AMT_FLAG = BaseConstant.IS_YESNO_YES;
                        }
						if (backAmt/100 > 0) {
							BACK_AMT_FLAG = BaseConstant.IS_YESNO_YES;
						}
					}
				}
				parms.put("BACK_AMT_FLAG", BACK_AMT_FLAG);
				parms.put("ZC_BACK_AMT_FLAG", ZC_BACK_AMT_FLAG);
				
			}else if(branchKey.equals("FLOW_0000_017_001_014_001")){//法务经理（汽车金融 ）:点击通过
				/**
				 * TODO 1.检验借款金额是否>=5000
				 */
				
				int BACK_AMT_FLAG = BaseConstant.IS_YESNO_NO;
				for (AssTrailCarDDTO assTrailCarDDTO : assTrailCarDDTOList) {
					if (assTrailCarDDTO.getBackAmt() != null) {
						Long backAmt = assTrailCarDDTO.getBackAmt();
						if (backAmt/100 > 5000) {
							BACK_AMT_FLAG = BaseConstant.IS_YESNO_YES;
						}
					}
				}
				parms.put("BACK_AMT_FLAG", BACK_AMT_FLAG);
				 
			}else if(branchKey.equals("FLOW_0000_017_001_006_001")||branchKey.equals("FLOW_0000_017_001_020_001")){//财务付款:点击通过FLAG=1
				/**
				 * TODO 1.检验是否填写实际付款时间及金额
				 */
				MessageDTO<AssTrailCarDInfDTO> messageDto = assTrailCarApi.findTrailCarDetailListByDetailIds(detailIdList);
				if (messageDto.isSuccess() &&  messageDto.getDatas() != null && messageDto.getDatas().size() >0) {
					infoList = messageDto.getDatas();
				for (AssTrailCarDInfDTO assTrailCarDInfDTO : infoList) {
					if (assTrailCarDInfDTO.getActPayDt() == null || "".equals(assTrailCarDInfDTO.getActPayDt())||assTrailCarDInfDTO.getActPayAmt() == null||"".equals(assTrailCarDInfDTO.getActPayAmt())) {
						throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_601, "请填写实际付款时间及金额");
					}
				}
				}else{
					throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_601, "拖车实际明细信息不存在.");
				}
			}else if(branchKey.equals("FLOW_0000_017_001_008_001")||branchKey.equals("FLOW_0000_017_001_015_001")){//记录拖车状态（重卡）、呈报人拖回标记（汽车金融）：点击通过
				/**
				 * TODO 1.检验是否记录了拖车状态（BACKED_FLAG_CD 1：已拖回  2：未拖回 3：无法拖回）
				 */
				int BACK_FLAG_CD_1 = BaseConstant.IS_YESNO_NO;
				int BACK_FLAG_CD_0 = BaseConstant.IS_YESNO_YES;
				ProductStatusLogDTO proDTO = null;
				List<ProductStatusLogDTO> proList = new ArrayList<ProductStatusLogDTO>();
				if(assTrailCarDDTOList != null && assTrailCarDDTOList.size() > 0){
					for (AssTrailCarDDTO assTrailCarDDTOTemp : assTrailCarDDTOList) {
						if(StringUtils.isEmpty(assTrailCarDDTOTemp.getBackedFlagCd()) || assTrailCarDDTOTemp.getBackedFlagCd().equals("0") || assTrailCarDDTOTemp.getBackedFlagCd().toString() == "0"){
							throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_601, "请标记拖车状态");
						}
						if (assTrailCarDDTOTemp.getBackedFlagCd().equals(InterfaceConstants.BACK_FLAG_CD_1)||assTrailCarDDTOTemp.getBackedFlagCd().toString() == "1") {//状态是否为已拖回
							BACK_FLAG_CD_1 = BaseConstant.IS_YESNO_YES;
						}
						if(assTrailCarDDTOTemp.getBackedFlagCd().equals(InterfaceConstants.BACK_FLAG_CD_2) || assTrailCarDDTOTemp.getBackedFlagCd().toString() == "2"||assTrailCarDDTOTemp.getBackedFlagCd().equals(InterfaceConstants.BACK_FLAG_CD_3)||assTrailCarDDTOTemp.getBackedFlagCd().toString() == "3"){
							BACK_FLAG_CD_0 = BaseConstant.IS_YESNO_NO;
							
							if (branchKey.equals("FLOW_0000_017_001_015_001")) {
								BaseLogUtils.newLogger("修改拖车状态start").setBussinessId("detailId:" + assTrailCarDDTOTemp.getId()).info();
								if(assTrailCarDDTOTemp.getBackedFlagCd().equals(InterfaceConstants.BACK_FLAG_CD_2)){//拖回标记：未拖回
									assTrailCarDDTOTemp.setBackStsCd(InterfaceConstants.BACK_STATUS_CD_4);//拖车状态：未拖回
								}
								if(assTrailCarDDTOTemp.getBackedFlagCd().equals(InterfaceConstants.BACK_FLAG_CD_3)){//拖回标记：无法拖回
									assTrailCarDDTOTemp.setBackStsCd(InterfaceConstants.BACK_STATUS_CD_5);//拖车状态：无法拖回
								}
								assTrailCarDDTOTemp.setFlowPassTm(new Date());
								result = assTrailCarApi.updateAssTrailCarDetailInfo(assTrailCarDDTOTemp);
								if (!result.isSuccess()) {
									throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_603, "修改拖车状态失败");
								}
								BaseLogUtils.newLogger("修改拖车状态end").setBussinessId("detailId:" + assTrailCarDDTOTemp.getId()).info();
							}
							
							if(assTrailCarDDTOTemp.getBackedFlagCd().equals(InterfaceConstants.BACK_FLAG_CD_2)){
								proDTO = new ProductStatusLogDTO();
								proDTO.setCurrentStatus(InterfaceConstants.PAY_STATUS_CD_S01);
								proDTO.setPrjPrdId(assTrailCarDDTOTemp.getPrjPrdDtlId());
								proDTO.setOpCode(InterfaceConstants.OP_CODE_OP0020);
								proDTO.setProcessInstanceCode(procDefKey);
								proDTO.setProcessInstanceId(procInstId);
								proList.add(proDTO);
							}
							if(assTrailCarDDTOTemp.getBackedFlagCd().equals(InterfaceConstants.BACK_FLAG_CD_3)){
								proDTO = new ProductStatusLogDTO();
								proDTO.setCurrentStatus(InterfaceConstants.PAY_STATUS_CD_S010601);
								proDTO.setPrjPrdId(assTrailCarDDTOTemp.getPrjPrdDtlId());
								proDTO.setOpCode(InterfaceConstants.OP_CODE_OP0020);
								proDTO.setProcessInstanceCode(procDefKey);
								proDTO.setProcessInstanceId(procInstId);
								proList.add(proDTO);
							}	
						}
					}
					if (!proList.isEmpty() && proList.size() > 0) {
						BaseLogUtils.newLogger("更新支付表状态start").info();
						result = this.assTrailCarApi.updatePayStatus(proList);
						if (!result.isSuccess()) {
							throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_603, "更新支付表的状态失败.");
						}
                        BaseLogUtils.newLogger("更新支付表状态end").info();
					}
				} else {
					throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_601, "拖车明细信息不存在.");
				}
				
				parms.put("BACK_FLAG_CD_1",BACK_FLAG_CD_1);
				parms.put("BACK_FLAG_CD_0",BACK_FLAG_CD_0);
                if (BACK_FLAG_CD_1 == 1) {
                    Long recentParkMgId = this.assParkingMgService.getRecentParkMg(assTrailCarMDTO.getParkId());
                    if (StringUtils.isNotEmpty(recentParkMgId)) {
                        String[] str = {String.valueOf(recentParkMgId)};
                        parms.put("nextAssignee", str);
                    } else {
                        parms.put("nextAssignee", null);
                    }
                }

				parms.put("REJECT", BaseConstant.IS_YESNO_NO);
				
				if (branchKey.equals("FLOW_0000_017_001_015_001") && BACK_FLAG_CD_0 == 0 && BACK_FLAG_CD_1 != 1) {//乘用车，标记为未拖回或无法拖回，流程结束
					this.pass(flowCompleteParamsDTO);
				}
			}else if(branchKey.equals("FLOW_0000_017_001_017_002") || branchKey.equals("FLOW_0000_017_001_009_002")){//资产管理员入库/资产管理员入库1：驳回
				parms.put("REJECT", BaseConstant.IS_YESNO_YES);
			}else if(branchKey.equals("FLOW_0000_017_001_011_001")||branchKey.equals("FLOW_0000_017_001_018_001")){//优车系统管理员核查入库情况、优车系统管理员核查入库情况1:点击已入库
				if(branchKey.equals("FLOW_0000_017_001_011_001")){
                    /**
                     * 1.检验借款金额是否>0
                     */
                    int BACK_AMT_FLAG = BaseConstant.IS_YESNO_NO;
                    for (AssTrailCarDDTO assTrailCarDDTO : assTrailCarDDTOList) {
                        if (assTrailCarDDTO.getBackAmt() != null) {
                            Long backAmt = assTrailCarDDTO.getBackAmt();
                            if (backAmt/100 > 0) {
                                BACK_AMT_FLAG = BaseConstant.IS_YESNO_YES;
                            }
                        }
                    }
                    parms.put("BACK_AMT_FLAG", BACK_AMT_FLAG);

					//校验市场评估价和市场评估时间必填
                    BaseLogUtils.newLogger("查询拖车实际明细信息").setBussinessId("trailerId:" + trailer_id).info();
					MessageDTO<AssTrailCarDInfDTO> messageDto = assTrailCarApi.findTrailCarDetailListByDetailIds(detailIdList);
					if (messageDto.isSuccess() &&  messageDto.getDatas() != null && messageDto.getDatas().size() >0) {
						infoList = messageDto.getDatas();
						for (AssTrailCarDInfDTO assTrailCarDInfDTO : infoList) {
							if(null==assTrailCarDInfDTO || null==assTrailCarDInfDTO.getMarketAmt() || null==assTrailCarDInfDTO.getMarketDt()){
								throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_601, "市场评估价和市场评估时间必填.");
							}
						}
					}else{
						throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_601, "拖车实际明细信息不存在.");
					}
				}
				/**
				 * TODO 1.修改入库状态、入库时间等:已入库
				 *      2.修改入库单的状态：已验证
				 *      3.修改支付表中的拖车状态、拖回日期：已拖回
				 */
				if(assTrailCarDDTOList != null && assTrailCarDDTOList.size() > 0){
					for (AssTrailCarDDTO assTrailCarDDTO : assTrailCarDDTOList) {
						assTrailCarDDTO.setIsEnter(InterfaceConstants.IS_ENTER_1);
						assTrailCarDDTO.setEnterTm(new Date());
						assTrailCarDDTO.setActBackDt(new Date());
					    result = assTrailCarApi.updateAssTrailCarDetailInfo(assTrailCarDDTO);
						if (!result.isSuccess()) {
							throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_603, "修改入库状态失败.");
						}
					}
					MessageDTO<AssTrailCarDInfDTO> assTrailCarDInfDTO = assTrailCarApi.findTrailCarDetailListByDetailIds(detailIdList);
					if (assTrailCarDInfDTO.isSuccess()&& assTrailCarDInfDTO.getDatas()!=null && assTrailCarDInfDTO.getDatas().size() > 0) {
						infoList = assTrailCarDInfDTO.getDatas();
						for (AssTrailCarDInfDTO assTrailCarDInfDTOTemp : infoList) {
							assTrailCarDInfDTOTemp.setActBackDt(new Date());
							result = assTrailCarApi.modifyTrailCarDInf(assTrailCarDInfDTOTemp);
							if (!result.isSuccess()) {
								throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_603, "修改实际拖回日期失败.");
							}
						}
						
					}else{
						throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_601, "查询信息失败");
					}
				}else{
					throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_601, "拖车明细信息不存在.");
				}
			
				List<ProductStatusLogDTO> proList = new ArrayList<ProductStatusLogDTO>();
				ProductStatusLogDTO proDTO = null;
				if(assTrailCarDDTOList != null && assTrailCarDDTOList.size() > 0){
					for (AssTrailCarDDTO assTrailCarDDTO : assTrailCarDDTOList) {
						BaseLogUtils.newLogger("修改入库附件的状态Start").setKeys("detailId:" + assTrailCarDDTO.getId()).info();
						SysUlFilesRecQueryCondition qc = new SysUlFilesRecQueryCondition();
						qc.setPkId(String.valueOf(assTrailCarDDTO.getId()));//主数据ID
						qc.setTabNm(AssFileConstant.ASS_TRAIL_CAR_D_TABNM);//主数据表明
						qc.setSysCd(flowCompleteParamsDTO.getSysCd());//系统代码-必须条件
						qc.setCfgCd(AssFileConstant.ASS_TRAIL_CAR_CFGCD);//拖车模块
						qc.setCfgDtlCd(AssFileConstant.ASS_TRAIL_CAR_CFGDTLCD_30);//入库单
						List<SysUlFilesRecDTO> list = this.uploadApiService.searchSysUlFilesRecList(qc);
						if (list == null || list.size() < 1) {
							throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_601, "更新入库单验证状态失败--请先上传入库单附件.");
						}else{
                            qc.setAudStsCd(AssFileConstant.AUD_STS_CD_1);//验证通过
                            boolean flag = this.uploadApiService.modifyAudStsCd(qc);
                            if (!flag) {
                                throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_603, "更新入库单验证状态失败.");
                            }
						}
                        BaseLogUtils.newLogger("修改入库附件的状态end").setKeys("detailId:" + assTrailCarDDTO.getId()).info();

					    proDTO = new ProductStatusLogDTO();
						proDTO.setCurrentStatus(InterfaceConstants.PAY_STATUS_CD_S010602);//已拖回
						proDTO.setPrjPrdId(assTrailCarDDTO.getPrjPrdDtlId());
						proDTO.setOpCode(InterfaceConstants.OP_CODE_OP0020);//拖车申请通过
						proDTO.setProcessInstanceCode(procDefKey);
						proDTO.setProcessInstanceId(procInstId);
						proList.add(proDTO);
					}
					
					BaseLogUtils.newLogger("修改支付表状态：start").info();
					result = this.assTrailCarApi.updatePayStatus(proList);
					if (!result.isSuccess()) {
						throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_603, "更新支付表的状态失败.");
					}
                    BaseLogUtils.newLogger("修改支付表状态：end").info();
					for (AssTrailCarDDTO assTrailCarDDTO : assTrailCarDDTOList) {
                        BaseLogUtils.newLogger("支付表状态为已拖回，向权证接口传送数据start").setKeys("masterId:" + assTrailCarDDTO.getMasterId(), "detailId:" + assTrailCarDDTO.getId()).info();
                        if (assTrailCarDDTO.getBackedFlagCd().equals(InterfaceConstants.BACK_FLAG_CD_1)) {//拖回标记：已拖回
                            Long projectId = assTrailCarDDTO.getPrjId();
                            String paylistCode = assTrailCarDDTO.getPaySchNo();//支付表编号
                            String status = InterfaceConstants.PAY_STATUS_CD_S010602;
                            Date endDate = null;//结清日期可以为空
                            fl.inf.facade.dto.MessageDTO<String> response = warrantApiService.changePayStatus(projectId, paylistCode, status, endDate);
                            if (!response.isSuccess()) {
                                throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_603, "===向权证接口传送数据失败===.");
                            }
                        }
                    }
                    BaseLogUtils.newLogger("支付表状态为已拖回，向权证接口传送数据end").info();
				}
				// 新增借款数据及流程历史
                this.assTrailCarDService.addFinLoadInfoAndFlowHistory(trailer_id, flowCompleteParamsDTO);
			}else if( branchKey.equals("FLOW_0000_017_001_007_001") || branchKey.equals("FLOW_0000_017_001_012_001") || branchKey.equals("FLOW_0000_017_001_021_001")){
			    //财务做账、财务做账1：通过
			}else if(branchKey.equals("FLOW_0000_017_001_011_002")||branchKey.equals("FLOW_0000_017_001_018_002")){//优车系统管理员核查入库情况：驳回
                Long recentParkMgId = this.assParkingMgService.getRecentParkMg(assTrailCarMDTO.getParkId());
                if (StringUtils.isNotEmpty(recentParkMgId)) {
                    String[] str = {String.valueOf(recentParkMgId)};
                    parms.put("nextAssignee", str);
                } else {
                    parms.put("nextAssignee", null);
                }
			}else if(branchKey.equals("FLOW_0000_017_001_013_001")||branchKey.equals("FLOW_0000_017_001_022_001")){//财务估算保底价、保底价核算:点击通过
				/**
				 * TODO 1.检验是否填写保底价款
				 * 		2.若填写，修改拖车状态，流程通过的时间，流程结束
				 */
				//检验是否填写保底价款
				BaseLogUtils.newLogger("查询拖车实际明细信息Start").setKeys(JSON.toJSONString(detailIdList)).info();
				MessageDTO<AssTrailCarDInfDTO> assTrailCarDInfDTO = assTrailCarApi.findTrailCarDetailListByDetailIds(detailIdList);
				if (assTrailCarDInfDTO.isSuccess()&& assTrailCarDInfDTO.getDatas()!=null && assTrailCarDInfDTO.getDatas().size() > 0) {
					infoList = assTrailCarDInfDTO.getDatas();
					for (AssTrailCarDInfDTO assTrailCarDInfDTOTemp : infoList) {
						if (assTrailCarDInfDTOTemp.getBaseAmt() == null || "".equals(assTrailCarDInfDTOTemp.getBaseAmt())) {//一次性保底价
							throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_601, "请填写保底价款");
						}
					}
				}else{
					throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_601, "查询信息失败");
				}
				//this.flowSuccess(assTrailCarDDTOList);
			}
			switch (branchKey) {
//                case "FLOW_0000_017_001_005_001"://财务总监审核 提交
//                case "FLOW_0000_017_001_019_001":

                case "FLOW_0000_017_001_013_001"://财务估算保底价:通过
                    updateLoanFlowAndAddPayFee(assTrailCarDDTOList,flowCompleteParamsDTO);
                    this.flowSuccess(assTrailCarDDTOList);
                    break;
                case "FLOW_0000_017_001_012_001"://财务做账1:通过
                    this.flowSuccess(assTrailCarDDTOList);
                    break;
                case "FLOW_0000_017_001_008_002"://记录拖车状态:不通过
                    this.flowFail(assTrailCarDDTOList,procDefKey,procInstId);
                    break;
                case "FLOW_0000_017_001_003_002"://发起人:不通过
                    this.flowFail(assTrailCarDDTOList,procDefKey,procInstId);
                    break;
                case "FLOW_0000_017_001_022_001"://乘用车保底价核算:通过
                    this.flowSuccess(assTrailCarDDTOList);
                    break;
                case "FLOW_0000_017_001_031_002"://异常处理 处理
                    getDeal(trailer_id);
                    break;
                case "FLOW_0000_017_001_034_002"://异常处理 处理
                    getDeal(trailer_id);
                    break;

                case "FLOW_0000_017_001_031_001"://异常处理 核查无误
                    getAgen(trailer_id);
                    break;
                case "FLOW_0000_017_001_034_001"://异常处理 核查无误
                    getAgen(trailer_id);
                    break;

                default:
                    break;
		   }
		}
	
		
		return parms;
	}

	/**
	 * 核查无误后自动通过放款中节点
	 * 流程实例ID
	 * @param procInstId
	 */
	private void passPay(String procInstId, Map<String, Object> params, String taskDefKey){
		com.lionbridge.activiti.dto.MessageDTO<String> dto = WorkflowClient.completeTaskByTaskDefKey(
				procInstId
				, taskDefKey, params);
		BaseLogUtils.newLogger("核查无误后自动通过放款中节点").setKeys("dto:" + JSON.toJSONString(dto)).info();
	}

    @Override
    public void executeAfter(FlowCompleteParamsDTO flowCompleteParamsDTO) throws BaseException {
        String branchKey = flowCompleteParamsDTO.getBranchKey();
        Long trailer_id = flowCompleteParamsDTO.getBusinessKey();
        String procInstId = flowCompleteParamsDTO.getProcInstId();
        List<AssTrailCarDDTO> assTrailCarDDTOList = assTrailCarApi.findTrailCarDetailListById(flowCompleteParamsDTO.getBusinessKey()).getDatas();
        if (StringUtils.isNotEmpty(branchKey)) {
            switch (branchKey) {
                case "FLOW_0000_017_001_013_001"://财务估算保底价:通过
                    this.pass(flowCompleteParamsDTO);
                    break;
                case "FLOW_0000_017_001_012_001"://财务做账1:通过
                    this.pass(flowCompleteParamsDTO);
                    break;
                case "FLOW_0000_017_001_008_002"://记录拖车状态:不通过
                    this.noPass(flowCompleteParamsDTO);
                    break;
                case "FLOW_0000_017_001_003_002"://发起人:不通过
                    this.noPass(flowCompleteParamsDTO);
                    break;
                case "FLOW_0000_017_001_022_001"://乘用车保底价核算:通过
                    if (CollectionUtils.isNotEmpty(assTrailCarDDTOList)) {
                        updateLoanFlowAndAddPayFee(assTrailCarDDTOList, flowCompleteParamsDTO);
                    }
                    this.pass(flowCompleteParamsDTO);
                    break;
		        case "FLOW_0000_017_001_031_001":// 左边分支通过放款中节点（重卡、优车、专车）
                    int agen = this.getAgen(trailer_id);
                    if (agen == 0) {
                        Map<String, Object> params = new HashMap<String, Object>();
                        params.put("returnResult", "success");
                        this.passPay(procInstId, params, "auto_complete_task_loan_0");
                    }
                    break;
                case "FLOW_0000_017_001_034_001":// 右边分支通过放款中节点（汽车金融）
                    int getAgen = this.getAgen(trailer_id);
                    if (getAgen == 0) {
                        Map<String, Object> params = new HashMap<String, Object>();
                        params.put("returnResult", "success");
                        this.passPay(procInstId, params, "auto_complete_task_loan_1");
                    }
                    break;
                default:
                    break;
            }
        }
    }

	@Override
	public String getFlowBusinessActMgrOrgCd(FlowCompleteParamsDTO flowCompleteParamsDTO) throws BaseException {
		Long trailer_id = flowCompleteParamsDTO.getBusinessKey();
		//拖车明细数据
		List<AssTrailCarDDTO> assTrailCarDDTOList = assTrailCarApi.findTrailCarDetailListById(trailer_id).getDatas();
		String cstMgrOrgCd = "";
		if (assTrailCarDDTOList != null && assTrailCarDDTOList.size() > 0) {
			Long prjId = assTrailCarDDTOList.get(0).getPrjId();
            BaseLogUtils.newLogger("流程回调实现类获取项目客户经理组织架构代码开始").setKeys("taskId:" + flowCompleteParamsDTO.getTaskId(), "prjId:" + prjId).info();
			if(null!=prjId){
				 cstMgrOrgCd = assTrailCarDMapper.selectCstMgrOrgCd(prjId);
				if (null == cstMgrOrgCd || cstMgrOrgCd.equals("")) {
                    BaseLogUtils.newLogger("根据ID未获取到业务数据!").info();
					throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_601, "根据ID未获取到业务数据!");
				}
                BaseLogUtils.newLogger("流程回调实现类获取项目客户经理组织架构代码结束").setKeys("taskId:" + flowCompleteParamsDTO.getTaskId(), "prjId:" + prjId, "cstMgrOrgCd:" + cstMgrOrgCd).info();
				return cstMgrOrgCd;
			}
		}
        BaseLogUtils.newLogger("流程接口回调>>返回项目客户经理组织架构>>未找到!").info();
		return super.getFlowBusinessActMgrOrgCd(flowCompleteParamsDTO);
	}
	/**
	 * 流程结束:通过
	 * @param flowCompleteParamsDTO
	 * @throws BaseException
	 */
	private void pass(FlowCompleteParamsDTO flowCompleteParamsDTO)throws BaseException{
		this.sysFlowSHService.modifyAudStsCd(InterfaceConstants.ASS_FLOW_S_H_ASS, FlowConstant.FLOW_CHECK_STATE_PASS, new Date(), new Date(),
				flowCompleteParamsDTO.getCrtUsrId(), flowCompleteParamsDTO.getBusinessKey(), flowCompleteParamsDTO.getProcDefKey(), 
				flowCompleteParamsDTO.getProcDefId(), flowCompleteParamsDTO.getSysCd(), flowCompleteParamsDTO.getProcInstId());
	}
	/**
	 * 流程结束:不通过
	 * @param flowCompleteParamsDTO
	 * @throws BaseException
	 */
	private void noPass(FlowCompleteParamsDTO flowCompleteParamsDTO)throws BaseException{
		this.sysFlowSHService.modifyAudStsCd(InterfaceConstants.ASS_FLOW_S_H_ASS, FlowConstant.FLOW_CHECK_STATE_NO_PASS, new Date(), new Date(),
				flowCompleteParamsDTO.getCrtUsrId(), flowCompleteParamsDTO.getBusinessKey(), flowCompleteParamsDTO.getProcDefKey(), 
				flowCompleteParamsDTO.getProcDefId(), flowCompleteParamsDTO.getSysCd(), flowCompleteParamsDTO.getProcInstId());
	}
	/**
	 * 申请通过
	 * @param assTrailCarDDTOList
	 * @throws BaseException
	 */
	private void flowSuccess(List<AssTrailCarDDTO> assTrailCarDDTOList)throws BaseException{
		MessageDTO<String>  result;
		for (AssTrailCarDDTO assTrailCarDDTO : assTrailCarDDTOList) {
			if (assTrailCarDDTO.getBackedFlagCd().equals(InterfaceConstants.BACK_FLAG_CD_1)) {//拖回标记：已拖回
				assTrailCarDDTO.setBackStsCd(InterfaceConstants.BACK_STATUS_CD_2);//拖车状态：已拖回
				//assTrailCarDDTO.setActBackDt(new Date());
			}
			if(assTrailCarDDTO.getBackedFlagCd().equals(InterfaceConstants.BACK_FLAG_CD_2)){//拖回标记：未拖回
				assTrailCarDDTO.setBackStsCd(InterfaceConstants.BACK_STATUS_CD_4);//拖车状态：未拖回
			}
			if(assTrailCarDDTO.getBackedFlagCd().equals(InterfaceConstants.BACK_FLAG_CD_3)){//拖回标记：无法拖回
				assTrailCarDDTO.setBackStsCd(InterfaceConstants.BACK_STATUS_CD_5);//拖车状态：无法拖回
			}
			assTrailCarDDTO.setFlowPassTm(new Date());
			BaseLogUtils.newLogger("修改拖车状态start").setKeys("detailId:" + assTrailCarDDTO.getId()).info();
			result = assTrailCarApi.updateAssTrailCarDetailInfo(assTrailCarDDTO);
			if (!result.isSuccess()) {
				throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_603, "修改拖车状态失败");
			}
            BaseLogUtils.newLogger("修改拖车状态end").setKeys("detailId:" + assTrailCarDDTO.getId()).info();
		}
	}
	/**
	 * 申请不通过
	 * @param
	 * @throws BaseException
	 */
	private void flowFail(List<AssTrailCarDDTO> assTrailCarDDTOList,String procDefKey,String procInstId)throws BaseException{
		MessageDTO<String>  result;
		ProductStatusLogDTO proDTO = null;
		List<ProductStatusLogDTO> proList = new ArrayList<ProductStatusLogDTO>();
		for (AssTrailCarDDTO assTrailCarDDTO : assTrailCarDDTOList) {
			assTrailCarDDTO.setBackStsCd(InterfaceConstants.BACK_STATUS_CD_3);//拖车状态：不通过
			//修改拖车申请表中拖车状态
			result = assTrailCarApi.updateAssTrailCarDetailInfo(assTrailCarDDTO);
			if (!result.isSuccess()) {
				throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_603, "修改拖车状态失败");
			}
			    proDTO = new ProductStatusLogDTO();
				proDTO.setCurrentStatus(InterfaceConstants.PAY_STATUS_CD_S01);
				proDTO.setPrjPrdId(assTrailCarDDTO.getPrjPrdDtlId());
				proDTO.setOpCode(InterfaceConstants.OP_CODE_OP0019);
				proDTO.setProcessInstanceCode(procDefKey);
				proDTO.setProcessInstanceId(procInstId);
				proList.add(proDTO);
		}
		BaseLogUtils.newLogger("更新支付表状态start").info();
		result = this.assTrailCarApi.updatePayStatus(proList);
		if (!result.isSuccess()) {
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_603, "更新支付表的状态失败.");
		}
        BaseLogUtils.newLogger("更新支付表状态end").info();
	}
	
	/**
	 * 核查无误 
	 * @param
	 * @return
	 */
	private int getAgen(Long id){
		List<FinPayDtlDTO> selectList = getFinPayDtlList(id);
		int res = 0;
		int flag =0;
		for (FinPayDtlDTO dto : selectList) {
			BaseLogUtils.newLogger("网银交易查询请求参数").setBussinessId("拖车流程&网银交易查询请求参数id:" + dto.getId()).info();
			InfBfsPayDTO ibpd = bFSApiService.selectByFlsNum(dto.getId());
            BaseLogUtils.newLogger("网银交易查询返回结果").setKeys(JSON.toJSONString(ibpd)).info();
			//调用网银接口
			if(null==ibpd
					|| "payFailure".equals(ibpd.getStatus())
					|| "sendFailure".equals(ibpd.getStatus())){
				flag ++;
			}
			// 非付款成功则不能通过放款中节点
			if(null ==ibpd || !"paySuccess".equals(ibpd.getStatus()) ){
				res =1;
			}
		}
		
		if(flag>0){
			if(env.equals("pro")){
				throw new BaseException("付款失败,请点击[处理]按钮");
			}
		}
		return res;
	}

	/**
	 * 处理
	 * @param
	 * @return
	 */
	private void getDeal(Long id){
		List<FinPayDtlDTO> selectList = getFinPayDtlList(id);
		int flag =0;
		for (FinPayDtlDTO dto : selectList) {
            BaseLogUtils.newLogger("拖车流程网银交易查询请求参数").setBussinessId("拖车流程&网银交易查询请求参数id:" + dto.getId()).info();
			InfBfsPayDTO ibpd = bFSApiService.selectByFlsNum(dto.getId());
            BaseLogUtils.newLogger("拖车流程网银交易查询返回结果").setKeys(JSON.toJSONString(ibpd)).info();
			//调用网银接口
			if(null==ibpd
					|| "payFailure".equals(ibpd.getStatus())
					|| "sendFailure".equals(ibpd.getStatus())){
				flag ++;
				if(env.equals("pro")){
                    BaseLogUtils.newLogger("拖车流程发送网银请求参数").setBussinessId("拖车流程&发送网银请求参数id:" + dto.getId()).info();
					fl.inf.facade.dto.MessageDTO<String> sendPay = bFSApiService.sendTrailCar(dto.getId());
                    BaseLogUtils.newLogger("拖车流程发送网银返回结果").setKeys("sendPay:" + JSON.toJSONString(sendPay)).info();
					if(sendPay == null || !sendPay.isSuccess()){
						throw new BaseException("网银发送失败");
					}
				}
			}
		}
		if(flag==0){
			if(env.equals("pro")){
				throw new BaseException("付款成功,请点击[核查无误]按钮");
			}
		}
	}

	/**
	 * 获取付款信息表
	 * @param id
	 * @return
	 */
	private List<FinPayDtlDTO> getFinPayDtlList(Long id){
		FinPayDtlQC  qc = new FinPayDtlQC();
		qc.setPayApplyId(id);
		qc.setIsDel(0L);
		BaseLogUtils.newLogger("条件查询付款明细表请求参数FinPayDtlId").setKeys(JSON.toJSONString(id)).info();
		List<FinPayDtlDTO> selectList = finPayDtlApiService.selectList(qc);
		if(CollectionUtils.isEmpty(selectList)){
			throw new BaseException("拖车流程添加的付款明细数据有误,付款申请id是:"+id);
		}
		return selectList;
	}
	
	private List<FinPayDtlDTO> selectFinPayDtlDTO(Long id){
		FinPayDtlQC qc = new FinPayDtlQC();
		qc.setPayApplyId(id);
		qc.setIsDel(0L);
        BaseLogUtils.newLogger("条件查询付款明细表请求参数FinPayDtlId").setKeys(JSON.toJSONString(id)).info();
		List<FinPayDtlDTO> selectList = finPayDtlApiService.selectList(qc);
		return selectList;
	}
	@Autowired
	private IFinLoanInfoApiService finLoanInfoService;
	private void updateLoanFlowAndAddPayFee(List<AssTrailCarDDTO> assTrailCarDDTOList,FlowCompleteParamsDTO flowCompleteParamsDTO) {
		FinPayApplyInfoDTO finPayADto = finPayApplyInfoApiService.selectById(flowCompleteParamsDTO.getBusinessKey());
		if(finPayADto != null){
			Long backAmt = assTrailCarDDTOList.get(0).getBackAmt();
			
			List<FinPayDtlDTO> selectFinPayDtlDTO = selectFinPayDtlDTO(flowCompleteParamsDTO.getBusinessKey());
			if(CollectionUtils.isEmpty(selectFinPayDtlDTO)){
				throw  new BaseException("拖车流程付款明细表数据有误:业务主键id"+flowCompleteParamsDTO.getBusinessKey());
			}
			if(backAmt>0){
				this.sysFlowSHService.modifyAudStsCd(FinFlowDynamicTableConstant.SPL_FLOW_S_H_CAP, FlowConstant.FLOW_CHECK_STATE_PASS, new Date(), new Date(),
						flowCompleteParamsDTO.getCrtUsrId(), flowCompleteParamsDTO.getBusinessKey(), flowCompleteParamsDTO.getProcDefKey(), 
						flowCompleteParamsDTO.getProcDefId(), flowCompleteParamsDTO.getSysCd(), flowCompleteParamsDTO.getProcInstId());
			}
			//修改付款申请表放款状态
			FinPayApplyInfoDTO dto = new FinPayApplyInfoDTO();
			dto.setId(flowCompleteParamsDTO.getBusinessKey());
			dto.setPayStsCd(FinPayApplyInfoConstant.LOAN_PASS);
			BaseLogUtils.newLogger("拖车流程修改付款信息表请求参数").setKeys("FinPayApplyInfoId:" + flowCompleteParamsDTO.getBusinessKey()).info();
			boolean modify = finPayApplyInfoApiService.modify(dto);
            BaseLogUtils.newLogger("拖车流程修改付款信息表返回结果").setKeys(JSON.toJSONString(modify)).info();

			FinPayApplyInfoDTO selectById = finPayApplyInfoApiService.selectById(flowCompleteParamsDTO.getBusinessKey());
			FinLoanInfoDTO infot = finLoanInfoService.selectById(selectById.getLoanId());
			FinPayApplyInfoQC  qc = new FinPayApplyInfoQC();
			qc.setLoanId(selectById.getLoanId());
			qc.setIsDel("0");
			List<FinPayApplyInfoDTO> selectList = finPayApplyInfoApiService.searchList(qc);
			//申请表统计放款金额
			Long succeAmt = 0L;
			for (FinPayApplyInfoDTO finPayApplyInfo : selectList) {
				if(finPayApplyInfo.getPayStsCd().equals("3")){
					succeAmt  +=finPayApplyInfo.getPayAmt();
				}
			}
			
			
			if(succeAmt.longValue() == infot.getLoanAmt().longValue()){
				//如果借款金额等于实付金额 修改借款记录表状态
				infot.setLoanStsCd("1");
			}else{
				infot.setLoanStsCd("0");
			}
			finLoanInfoService.updateFinLoanInfoDTO(infot);
		}
	}
	
	
	@Override
	public String executeFlowBack(FlowCompleteParamsDTO flowCompleteParamsDTO) throws BaseException {
        String taskDefKey = flowCompleteParamsDTO.getTaskDefKey();
        Long id = flowCompleteParamsDTO.getBusinessKey();
        BaseLogUtils.newLogger("java节点Start").setKeys("taskDefKey:" + taskDefKey, "id:" + id).info();
        switch (taskDefKey) {
            case "FLOW_0000_017_001_030"://发送网银
            case "FLOW_0000_017_001_033"://发送网银
                List<FinPayDtlDTO> selectList = getFinPayDtlList(id);
                int flag = 0;
                for (FinPayDtlDTO dto : selectList) {
                    BaseLogUtils.newLogger("拖车流程id&网银交易查询请求参数").setKeys(JSON.toJSONString(dto.getId())).info();
                    InfBfsPayDTO ibpd = bFSApiService.selectByFlsNum(dto.getId());
                    BaseLogUtils.newLogger("拖车流程id&网银交易查询返回结果").setKeys(JSON.toJSONString(dto.getId()), JSON.toJSONString(ibpd)).info();
                    //调用网银接口
                    if (null == ibpd
                            || "payFailure".equals(ibpd.getStatus())
                            || "sendFailure".equals(ibpd.getStatus())) {
                        if (env.equals("pro")) {
                            BaseLogUtils.newLogger("拖车流程id&发送网银请求参数").setKeys(JSON.toJSONString(dto.getId())).info();
                            fl.inf.facade.dto.MessageDTO<String> sendPay = bFSApiService.sendTrailCar(dto.getId());
                            BaseLogUtils.newLogger("拖车流程id&发送网银返回结果").setKeys(JSON.toJSONString(dto.getId()), JSON.toJSONString(sendPay)).info();
                            if (sendPay == null || !sendPay.isSuccess()) {
                                throw new BaseException("网银发送失败");
                            }
                        } else {
                            while (true) {
                                try {
                                    BaseLogUtils.newLogger("拖车流程id&发送网银请求参数").setKeys(JSON.toJSONString(dto.getId())).info();
                                    fl.inf.facade.dto.MessageDTO<String> sendPay = bFSApiService.sendTrailCar(dto.getId());
                                    BaseLogUtils.newLogger("拖车流程id&发送网银返回结果").setKeys(JSON.toJSONString(dto.getId()), JSON.toJSONString(sendPay)).info();
                                } catch (Exception e) {
                                    BaseLogUtils.newLogger("发送还款网银错误信息").setThrowable(e).info();
                                    break;
                                }
                            }
                        }
                    }
                    flag++;
                    if (flag == selectList.size()) {
                        break;
                    }
                }
                break;
            default:
                break;
        }
        return super.executeFlowBack(flowCompleteParamsDTO);
    }
}

